package com.restfinder.common.dao;

import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Projections;
import org.hibernate.criterion.Restrictions;
import org.hibernate.envers.AuditReader;
import org.hibernate.envers.AuditReaderFactory;
import org.hibernate.envers.query.AuditEntity;
import org.hibernate.envers.query.AuditQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.restfinder.model.IEntity;

@Repository
public abstract class StandardDAO<T extends IEntity> implements Serializable {

	private static final long serialVersionUID = 1L;
	
	public abstract Class getEntityClass();

	@Autowired
	protected SessionFactory sessionFactory;

	public void save(T entity) {
		sessionFactory.getCurrentSession().save(entity);
	}
	
	public void update(T entity) {
		sessionFactory.getCurrentSession().update(entity);
	}

	public void saveOrUpdate(T entity){
		sessionFactory.getCurrentSession().saveOrUpdate(entity);
	}

	public void delete(T entity){ 
		sessionFactory.getCurrentSession().delete(entity);
	}

	public T getById(long id) {
		return (T) sessionFactory.getCurrentSession().get(getEntityClass(), id);
	}

	public List<T> list(){
		Criteria criteria = sessionFactory.getCurrentSession().createCriteria(getEntityClass());
    	criteria.addOrder(Order.asc("id"));
        List<T> list = criteria.list();
        return list;
	}
}